package idv.loveloser.servlet;

import idv.loveloser.dao.MdlContext;
import idv.loveloser.dao.MdlContextDAO;
import idv.loveloser.dao.MdlCourseDAO;
import idv.loveloser.dao.MdlCourseModules;
import idv.loveloser.dao.MdlCourseModulesDAO;
import idv.loveloser.dao.MdlFiles;
import idv.loveloser.dao.MdlFilesDAO;
import idv.loveloser.dao.MdlFolder;
import idv.loveloser.dao.MdlFolderDAO;
import idv.loveloser.util.Util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class DownloadFiles extends HttpServlet {
	private MdlFolderDAO folderDAO=new MdlFolderDAO();
	private MdlCourseModulesDAO modulesDAO=new MdlCourseModulesDAO();
	private MdlContextDAO contextDAO = new MdlContextDAO();
	private MdlFilesDAO fileDAO = new MdlFilesDAO();
	private static final int CONTEXT_COURSE=50;
	/**
	 * Constructor of the object.
	 */
	public DownloadFiles() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		//response.setContentType("application/json");
		String client = request.getParameter("client");
		String sessionKey = request.getParameter("sessionKey");
		String courseId = request.getParameter("course");
		String sequence = request.getParameter("sequence");
		String filename=request.getParameter("filename");
		long contextId=-1L;
		List<MdlFiles> selectedFile = new ArrayList<MdlFiles>();
		
		MdlContext contextFound =null;
		if(Util.isAuthorised(client, sessionKey)){
			List<MdlContext> contexts=contextDAO.findByInstanceid(Long.parseLong(courseId));
			for(int index=0;index<contexts.size();index++){
				MdlContext context = contexts.get(index);
				if(context.getContextlevel()==CONTEXT_COURSE){
					contextFound=context;
					break;
				}
			}
			contexts=null;
			String contextPath = contextFound.getPath();
			contexts=contextDAO.findAll();
			for(int index=0;index<contexts.size();index++){
				MdlContext context = contexts.get(index);
				if(context.getPath().startsWith(contextPath)&& context.getInstanceid()==Long.parseLong(sequence)){
					contextId=context.getId();
					break;
				}
			}
			List<MdlFiles> files=fileDAO.findByContextid(contextId);
			
			for(int index=0;index<files.size();index++){
				MdlFiles file = files.get(index);
				if(file.getComponent().equalsIgnoreCase("mod_folder") && file.getFilearea().equalsIgnoreCase("content")&& file.getItemid()==0L && file.getMimetype()!=null){
					selectedFile.add(file);
				}
			}
			
//			MdlFolder folder=folderDAO.findById(Long.parseLong(folderId));
			
//			List<MdlCourseModules> modules= modulesDAO.findByCourse(Long.parseLong(courseId));
			
		}
		if(filename.length()==0){
			PrintWriter out = response.getWriter();
			Gson gson = new Gson();
			out.println(gson.toJson(selectedFile));
			out.flush();
			out.close();
		}else{
			String contentHash="";
			int length=0;
			for(int index=0;index<selectedFile.size();index++){
				MdlFiles file = selectedFile.get(index);
				if(file.getFilename().equalsIgnoreCase(filename)){
					contentHash=file.getContenthash();
					break;
				}
			}
			ServletOutputStream op       = response.getOutputStream();
			ServletContext      context  = getServletConfig().getServletContext();
			String              mimetype = context.getMimeType( filename );
			response.setContentType( (mimetype != null) ? mimetype :"application/octet-stream" );
			File downloadFile = new File(SystemSets.getStorage()+contentHash.substring(0,2)+System.getProperty("file.separator")+contentHash.substring(2,4)+System.getProperty("file.separator")+contentHash);
			response.setContentLength( (int)downloadFile.length() );
			response.setHeader( "Content-Disposition", "attachment; filename=\"" + filename+ "\"" );
			byte[] bbuf = new byte[1024];
			DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
			while ((in != null) && ((length = in.read(bbuf)) != -1)){
				op.write(bbuf,0,length);
			}
			in.close();
			op.flush();
			op.close();
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
